package gr.handmademarket.bl.operations;

import gr.handmademarket.hibernate.HibernateUtil;
import gr.handmademarket.po.enums.Role;
import gr.handmademarket.po.implementations.Buyer;
import gr.handmademarket.po.implementations.Seller;
import gr.handmademarket.po.interfaces.User;

import org.hibernate.Session;

/**
 * operation that saves a category.
 */
public class ChangePasswordOperation {

	private String username;

	private Role role;
	
	private String oldPassword;
	
	private String newPassword;
	
	private String retypePassword;
	
	/**
	 * Creates a new ChangePasswordOperation object. 
	 *
	 */
	public ChangePasswordOperation() {
	}
	
	/**
	 * execution method.
	 */
	@SuppressWarnings("nls")
	public void execute(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		if (Role.BUYER.equals(role)){
			Buyer buyer = (Buyer) session.get(Buyer.class, username);
			checkUser(buyer);
			session.update(buyer);
		}else{
			Seller seller = (Seller) session.get(Seller.class, username);
			checkUser(seller);
			session.update(seller);
		}
        session.getTransaction().commit();
	}
	
	private void checkUser(User user){
		if (user == null){
			throw new RuntimeException("user not found");
		} else if (!user.getPassword().equals(oldPassword)){
			throw new RuntimeException("old password was wrong");
		} else if (!newPassword.equals(retypePassword)){
			throw new RuntimeException("new password and retype password were not identical");
		} else if (newPassword.length() < 6){
			throw new RuntimeException("new password must be at least of six characters length");
		} 
		user.setPassword(newPassword);
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public void setRetypePassword(String retypePassword) {
		this.retypePassword = retypePassword;
	}
	
	public void setRole(Role role) {
		this.role = role;
	}

}
